<template>
  <div class="meeting-container">
    <!-- 侧边栏 -->
    <el-aside class="sidebar">
      <el-menu default-active="1" class="menu">
        <!-- 腾讯会议 -->
        <el-menu-item index="1" @click="activeSection = 'meeting'">
          <el-icon><DataBoard /></el-icon>
          <span>腾讯会议</span>
        </el-menu-item>
        <!-- 会议纪要 -->
        <el-menu-item index="2" @click="activeSection = 'notes'">
          <el-icon><Document /></el-icon>
          <span>会议纪要</span>
        </el-menu-item>
        <!-- 分析报告 -->
        <el-menu-item index="3" @click="activeSection = 'analysis'">
          <el-icon><DataLine /></el-icon>
          <span>分析报告</span>
        </el-menu-item>
        <!-- 评分 -->
        <el-menu-item index="4" @click="activeSection = 'scoring'">
          <el-icon><User /></el-icon>
          <span>讨论得分</span>
        </el-menu-item>
        <!-- 讨论区 -->
        <el-menu-item index="5" @click="activeSection = 'discussion'">
          <el-icon><Message /></el-icon>
          <span>讨论区</span>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 右侧主内容区 -->
    <el-main class="content">
      <!-- 腾讯会议 -->
      <el-card v-if="activeSection === 'meeting'" class="card">
        <template #header><span>腾讯会议</span></template>
        <el-button type="primary" @click="openMeetingLogin">
          进入腾讯会议
        </el-button>
      </el-card>

      <!-- 会议纪要：仅解析并展示TXT，不调用后端 -->
      <el-card v-if="activeSection === 'notes'" class="card">
        <template #header><span>上传会议纪要</span></template>
  <!-- 使用 label 包裹按钮和隐藏的 input -->
        <label class="file-upload-button">
          <el-button type="primary" @click="triggerFileSelect">选择文件</el-button>
          <input
            ref="hiddenInput"
            type="file"
            accept=".txt,.pdf,.docx"
            @change="handleFileUpload"
            style="display: none;"
          />
      </label>
      <div v-if="parsedContent" class="parsed-content">
        <h4><strong>文件内容预览：</strong></h4>
        <pre>{{ parsedContent }}</pre>
      </div>
    </el-card>

      <!-- 分析报告：点击“生成分析报告”才把文本传给后端 -->
      <el-card v-if="activeSection === 'analysis'" class="card">
        <template #header><span>智能助教分析结果</span></template>
        <el-button type="primary" @click="analyzeMeetingNotes" :loading="loading">
          生成分析报告
        </el-button>

        <!-- 分析结果展示 -->
        <div style="margin-top: 20px;" v-if="analysisResult">
          <!-- 如果 resultJson 存在，说明是可解析的JSON -->
          <div v-if="resultJson">
            <!-- 摘要 -->
            <h4><strong>会议摘要</strong></h4>
            <p>{{ resultJson.summary }}</p>

            <!-- 成员贡献分析 -->
            <h4><strong>成员贡献分析</strong></h4>
            <div
              v-for="(item, index) in resultJson.contributions"
              :key="index"
              style="margin-bottom: 30px;"
            >
              <strong>{{ item.姓名 }}</strong>
              <ul>
                <li>综合评分: {{ item["综合评分"] }}</li>
                <li>内容关联度: {{ item["内容关联度"] }}</li>
                <li>参与积极性: {{ item["参与积极性"] }}</li>
                <li>沟通表达能力: {{ item["沟通表达能力"] }}</li>
                <li>会议进程推动: {{ item["会议进程推动"] }}</li>
                <li>想法创新性: {{ item["想法创新性"] }}</li>
              </ul>
              <p>综合评价: {{ item["综合评价"] }}</p>

              <!-- 每个成员都有一个canvas -->
              <div class="radar-container">
                <canvas :id="'radarChart-' + index"></canvas>
              </div>
            </div>
          </div>
          <!-- 否则展示纯文本 -->
          <div v-else>
            <pre>{{ analysisResult }}</pre>
          </div>
        </div>
      </el-card>

      <!-- 讨论得分 -->
      <el-card v-if="activeSection === 'scoring'" class="card">
        <template #header><span>讨论得分</span></template>

        <!-- 评分数据表格 -->
        <el-table :data="groupScores" stripe class="custom-table">
          <el-table-column prop="username" label="成员姓名" width="200" />
          <el-table-column prop="negotiate" label="协商评分" width="200">
            <template #default="{ row }">
              <el-tag type="success">{{ row.negotiate }}</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 讨论区 -->
      <el-card v-if="activeSection === 'discussion'" class="card">
        <template #header><span>讨论区</span></template>
        <div class="discussion-form">
          <el-input
            type="textarea"
            v-model="newComment"
            placeholder="输入你的观点..."
            rows="3"
          ></el-input>
          <el-button type="primary" style="margin-top:10px;" @click="postComment">
            发布
          </el-button>
        </div>
        <div class="discussion-list" style="margin-top: 20px;">
          <div
            v-for="(comment, index) in discussionList"
            :key="index"
            class="discussion-item"
          >
            <el-card class="card" shadow="never">
              <p>{{ comment }}</p>
            </el-card>
          </div>
        </div>
      </el-card>
    </el-main>
  </div>
</template>

<script>
import axios from "axios";
import { useRoute } from "vue-router";
import { Chart } from "chart.js/auto";
import * as pdfjsLib from 'pdfjs-dist/build/pdf';
import mammoth from 'mammoth';
import {
  Document,
  DataBoard,
  DataLine,
  User,
  Message,
} from "@element-plus/icons-vue";

async function parsePDF(file) {
  const fileReader = new FileReader();
  return new Promise((resolve, reject) => {
    fileReader.onload = async function () {
      const typedarray = new Uint8Array(this.result);
      try {
        const pdf = await pdfjsLib.getDocument(typedarray).promise;
        let textContent = "";
        for (let i = 1; i <= pdf.numPages; i++) {
          const page = await pdf.getPage(i);
          const content = await page.getTextContent();
          const strings = content.items.map(item => item.str);
          textContent += strings.join(" ") + "\n";
        }
        resolve(textContent);
      } catch (err) {
        reject(err);
      }
    };
    fileReader.onerror = reject;
    fileReader.readAsArrayBuffer(file);
  });
}

async function parseDocx(file) {
  try {
    const arrayBuffer = await file.arrayBuffer();
    const result = await mammoth.extractRawText({ arrayBuffer });
    return result.value;
  } catch (err) {
    throw err;
  }
}

export default {
  name: "MeetingDiscussion",
  components: { Document, DataBoard, DataLine, User, Message },
  data() {
    return {
      activeSection: "meeting", // 默认打开腾讯会议
      parsedContent: "",       // 存储TXT解析后的文本
      analysisResult: "",      // 原始后端返回的数据（可能是纯文本或JSON）
      resultJson: null,        // 如果能JSON.parse成功，则存这里
      studentScore: null,
      loading: false,
      newComment: "",
      discussionList: [],
      radarCharts: [],         // 存储多个雷达图实例
      groupScores: [], // 存储从后端获取的评分数据
    };
  },
  mounted() {
    // 获取 taskId 和 groupId
    const route = useRoute();
    this.taskId = route.query.taskId;
    this.groupId = route.query.groupId;
    this.sysUserId = route.query.sysUserId;

    console.log("taskId:", this.taskId, "groupId:", this.groupId, "sysUserId:", this.sysUserId);

    // 获取小组成员的 negotiate 分数
    this.fetchGroupScores();
  },
  methods: {
    triggerFileSelect() {
      this.$refs.hiddenInput.click();
    },
    // 腾讯会议
    openMeetingLogin() {
      window.open("https://meeting.tencent.com/", "_blank");
    },

    async handleFileUpload(e) {
  const file = e.target.files[0];
  if (!file) return;
  const fileExtension = file.name.split('.').pop().toLowerCase();
  try {
    if (fileExtension === "txt") {
      const reader = new FileReader();
      reader.onload = (evt) => {
        this.parsedContent = evt.target.result;
      };
      reader.readAsText(file, "utf-8");
    } else if (fileExtension === "pdf") {
      this.parsedContent = await parsePDF(file);
    } else if (fileExtension === "docx") {
      this.parsedContent = await parseDocx(file);
    } else {
      this.$message.error("暂不支持该文件格式！");
    }
  } catch (error) {
    console.error("文件解析失败：", error);
    this.$message.error("文件解析失败！");
  }
},

    // 生成分析报告：点击时把parsedContent发给后端
    async analyzeMeetingNotes() {
      if (!this.parsedContent) {
        this.$message.warning("请先上传并解析文件内容！");
        return;
      }
      this.loading = true;
      try {
        const response = await axios.post("/api/deepseek-analyze_meeting_notes", {
          text: this.parsedContent,
          group_id: this.groupId,
          task_id: this.taskId,
          sysuser_id: this.sysUserId,
        });
        let analysisData = response.data.analysis;

        // 如果返回的是字符串，则尝试解析
        if (typeof analysisData === "string") {
          try {
            analysisData = JSON.parse(analysisData);
          } catch (err) {
            console.warn("无法解析返回字符串为 JSON, 使用原字符串:", err);
          }
        }

        // 保留原始文本显示
        this.analysisResult = response.data.analysis;

        // 如果解析成功，存入 resultJson 用于可视化
        if (
            typeof analysisData === "object" &&
            analysisData.summary &&
            analysisData.contributions
        ) {
          this.resultJson = analysisData; // 先赋值

          console.log("分析结果：", analysisData);

          // 等 Vue 把模板更新完毕后再绘制雷达图
          this.$nextTick(() => {
            this.destroyAllRadarCharts(); // 清空之前的图表实例
            // 针对每个成员都绘制一个雷达图
            this.resultJson.contributions.forEach((item, index) => {
              this.createRadarChart(item, index);
            });
          });
        } else {
          this.resultJson = null;
        }
      } catch (error) {
        console.error(error);
        this.analysisResult = "调用 Deepseek 失败";
      } finally {
        this.loading = false;
      }
    },

    // 清除之前的图表
    destroyAllRadarCharts() {
      if (this.radarCharts.length > 0) {
        this.radarCharts.forEach(chart => chart.destroy());
        this.radarCharts = [];
      }
    },

    // 绘制雷达图（对每个成员调用一次）
    createRadarChart(memberData, index) {
      // 获取 <canvas> 元素
      const canvasId = "radarChart-" + index;
      const canvas = document.getElementById(canvasId);
      if (!canvas) {
        console.warn(`未找到id为 ${canvasId} 的 canvas 元素`);
        return;
      }

      const ctx = canvas.getContext("2d");
      if (!ctx) {
        console.warn("无法获取 2D context");
        return;
      }

      const labels = [
        "内容关联度",
        "参与积极性",
        "沟通表达能力",
        "会议进程推动",
        "想法创新性",
      ];
      const dataValues = [
        memberData["内容关联度"] || 0,
        memberData["参与积极性"] || 0,
        memberData["沟通表达能力"] || 0,
        memberData["会议进程推动"] || 0,
        memberData["想法创新性"] || 0,
      ];
      const memberName = memberData["姓名"] || "未知成员";

      console.log("雷达图数据：", memberName, dataValues);

      // 创建雷达图
      const radarChart = new Chart(ctx, {
        type: "radar",
        data: {
          labels,
          datasets: [
            {
              label: memberName + " 评分雷达图",
              data: dataValues,
              backgroundColor: "rgba(54, 162, 235, 0.2)",
              borderColor: "rgba(54, 162, 235, 1)",
              borderWidth: 1,
            },
          ],
        },
        options: {
          scales: {
            r: {
              min: 0,
              max: 100,
              ticks: {
                stepSize: 1,
              },
            },
          },
        },
      });
      // 保存图表实例，便于后续销毁
      this.radarCharts.push(radarChart);
    },


    // 发布讨论
    postComment() {
      if (!this.newComment.trim()) {
        this.$message.warning("请输入内容后再发布");
        return;
      }
      this.discussionList.push(this.newComment.trim());
      this.newComment = "";
    },
    async fetchGroupScores() {
      try {
        const response = await axios.get("http://39.105.217.183:8000/api/get-group-negotiate-scores/", {
          params: {
            task_id: this.taskId,
            group_id: this.groupId,
          },
        });

        // 假设后端返回的数据格式:
        // [
        //   { "username": "张三", "negotiate": 8.5 },
        //   { "username": "李四", "negotiate": 7.0 }
        // ]
        this.groupScores = response.data;
        console.log("获取小组讨论得分:", this.groupScores);
      } catch (error) {
        console.error("获取小组得分失败:", error);
      }
    },
  },
};
</script>

<style scoped>
.meeting-container {
  display: flex;
  min-height: 100vh; /* 页面高度自适应 */
  width: 1000px;
  background-color: #f0f2f5; /* 背景浅灰 */
}

/* 侧边栏 */
.sidebar {
  width: 220px;
  background: #f5f5f5;
  padding-top: 20px;
  border-right: 1px solid #ebeef5;
}

/* El-Menu */
.menu {
  border-right: none;
}

/* 右侧内容区 */
.content {
  flex: 1;
  padding: 20px; /* 只留 20px 内边距，避免顶部过大空白 */
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  width: 100%;
  max-width: 1200px; /* 最大宽度，防止超大屏幕时行太长 */
  margin: 0 auto; /* 居中显示 */
  background: #fff; /* 白色底板，让卡片不会太贴近灰色背景 */
}

/* 通用卡片 */
.card {
  width: 100%;       /* 占据 content 的全部宽度 */
  max-width: 100%;   /* 不再限制为 500px，避免过窄 */
  margin-bottom: 20px;
  /* 内部留一定 padding，避免贴边 */
}

/* 上传文件的 input 样式，让按钮更美观 */
input[type="file"] {
  display: inline-block;
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  color: #606266;
  font-size: 14px;
  margin-bottom: 10px;
}

/* 解析内容区域：适当增大高度 */
.parsed-content {
  background: #f9f9f9;
  padding: 15px;
  margin-top: 10px;
  border-radius: 8px;
  max-height: 400px; /* 增加到400px */
  overflow-y: auto;
}

/* 讨论区表单 */
.discussion-form {
  margin-bottom: 10px;
  width: 100%; /* 让输入框和按钮可用更大空间 */
}

.discussion-form .el-input {
  width: 100%; /* 保证输入框足够宽 */
}

/* 讨论列表中的卡片也可撑满 */
.discussion-list .card {
  width: 100%;
  margin-bottom: 10px;
}

/* 雷达图容器，让其有一定的高度和宽度，并居中 */
.radar-container {
  margin-top: 10px;
  width: 100%;
  min-height: 400px;
  max-width: 800px;
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center;     /* 如果需要垂直居中 */
  background: #fafafa;     /* 可选，给雷达图区域浅底色 */
  border-radius: 8px;      /* 可选，视觉优化 */
}

/* 小屏幕适配 */
@media (max-width: 768px) {
  .meeting-container {
    flex-direction: column;
  }
  .sidebar {
    width: 100%;
    border-right: none;
    border-bottom: 1px solid #ebeef5;
    display: flex;
  }
  .content {
    padding: 10px;
    max-width: 100%;
    margin: 0 auto;
  }

  .file-upload-button {
  display: inline-block;
  cursor: pointer;
}

}
</style>